package com.pp.demo.module.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.pp.demo.module.api.entity.SeckillActivity;
import com.pp.demo.module.api.mapper.SeckillActivityMapper;
import com.pp.demo.module.api.service.SeckillActivityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author pzh
 * @since 2025-07-14 09:45:25
 */
@Service
public class SeckillActivityServiceImpl extends ServiceImpl<SeckillActivityMapper, SeckillActivity> implements SeckillActivityService {

    @Override
    public List<SeckillActivity> listValidActivities(Boolean status, LocalDateTime now) {
        LambdaQueryWrapper<SeckillActivity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SeckillActivity::getStatus, status)
                .le(SeckillActivity::getStartTime, now)
                .ge(SeckillActivity::getEndTime, now);

        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public int decreaseStock(long activityId) {
        LambdaUpdateWrapper<SeckillActivity> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.setSql("stock = stock - 1")
                .eq(SeckillActivity::getId, activityId)
                .gt(SeckillActivity::getStock, 0);

        return baseMapper.update(null, updateWrapper);
    }
}
